<?php
/**
 * Created by PhpStorm.
 * User: song
 * Email: zousong@yiban.cn
 * Date: 16/5/12
 * Time: 下午9:07
 */
namespace App\Library;


class CaptchaCode
{
    private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//随机因子
    private $code;//验证码
    public $codelen = 6;//验证码长度

    private $width = 130;//宽度  130
    private $height = 50;//高度   50

    private $img;//图形资源句柄
    private $font;//指定的字体
    private $fontsize = 26;//指定字体大小
    private $fontcolor;//指定字体颜色

    //构造方法初始化
    public function __construct($length = 6)
    {
        //3还行先留着；4特别难认，将原先的9更名为4；其他字体不动。将9个字体变更为8个字体。
        $this->font = public_path('/static/font/f_' . rand(1, 4) . '.ttf');

        $this->codelen = $length ?: 6;

        $this->createBg();
        $this->createCode();
        $this->createLine();
        $this->createFont();
    }

    //生成随机码
    private function createCode()
    {
        $this->code = substr(str_shuffle($this->charset), 0, $this->codelen);
    }

    //生成背景
    private function createBg()
    {
        $this->img = imagecreatetruecolor($this->width, $this->height);
        //$color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
        $color = imagecolorallocate($this->img, mt_rand(255, 255), mt_rand(255, 255), mt_rand(255, 255));
        imagefilledrectangle($this->img, 0, $this->height, $this->width, 0, $color);
    }

    //生成文字
    private function createFont()
    {
        //$_x = $this->width / $this->codelen ;
        $_x = $this->width / ($this->codelen + 1);  //$_x为每个字占据的宽度，可以间接调整最右边那个字距离右边的距离。

        for ($i = 0; $i < $this->codelen; $i++) {
            $this->fontcolor = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));

            imagettftext($this->img, $this->fontsize, mt_rand(-20, 20), $_x * $i + 10, $this->height / 1.4, $this->fontcolor, $this->font, $this->code[$i]);
            //$_x*$i调整第一个字距离左侧距离
        }
    }

    //生成线条、雪花
    private function createLine()
    {
        //线条
        for ($i = 0; $i < 6; $i++) {
            $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
            imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
        }
        //雪花
        for ($i = 0; $i < 100; $i++) {
            $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
            imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->height), '*', $color);
        }
    }

    //输出
    public function outPut()
    {
//        header('Cache-Control:no-cache,must-revalidate');
//        header('Pragma:no-cache');
//        header('Content-type:image/png');
        imagepng($this->img);
        imagedestroy($this->img);
    }

    //获取验证码
    public function getCode()
    {
        return strtolower($this->code);
    }
}
